require "Common/define"
require "Logic/Config"
require "Common/functions"

ChatMsgItem = {};
HelperFunc.SetUIEnv(ChatMsgItem)
local this = ChatMsgItem;

this.time = nil;
this.timeObj = nil;

this.otherIcon = nil;
this.otherName = nil;
this.otherDialog = nil;
this.otherTitle = nil;

this.myIcon = nil;
this.myName = nil;
this.myDialog = nil;
this.myTitle = nil;
this.chatMsgCtrl = nil;
this.timeCtrl = nil;
this.levelText = nil
this.minute = nil;
local daytime = 24 * 60 * 60;
local firsttime = 0;
local default_color = Color.HexToColor("#F1FFF9")
function ChatMsgItem.Init()
    local name, packageName = getUIName(PanelNames.ChatMsgItem);
    panelMgr:Push(name, packageName, this.OnCreate,Config.useLocalUI);
end

function ChatMsgItem.onCreate(obj)
end

function ChatMsgItem.initData(obj,data,isMiniPanel)

    time = obj:GetChild("time");
    time2 = obj:GetChild("time2")
    otherIcon = obj:GetChild("otherIcon")
    --if otherIcon then
    --    otherIcon = otherIcon:GetChild("icon");
    --end
    otherName = obj:GetChild("otherName");
    otherDialog = obj:GetChild("otherDialog");
    otherTitle = obj:GetChild("Badge");
    this.otherLBS = obj:GetChild("otherLBS");

    myIcon = obj:GetChild("myIcon"):GetChild("head"):GetChild("HeadIcon");
    myIconFrame = obj:GetChild("myIcon"):GetChild("frame");

    myName = obj:GetChild("myName");
    myDialog = obj:GetChild("myDialog");
    myTitle =  obj:GetChild("myBadge");
    levelText = obj:GetChild("Level")
    chatMsgCtrl = obj:GetController("chatMsgCtrl");
    timeCtrl = obj:GetController("timeCtrl");
    otherDialog.text = ""
    myDialog.text = ""
    --时间间隔长度
    minute = G.dataTable["t_global"][tostring(43)].f_int_value * 60;
    if levelText then
        levelText.text = ""
        obj:GetChild("n21").visible = false
    end
    -- 功能没有，暂时注释
    if otherIcon then
        otherIcon.onClick:Clear();
        otherIcon.onClick:Add(function()
            if data.serverId == Config.chatServerId then
                roleInfoHandler.sendreqOtherRoleInfo(data.roleId);
            end
        end)
    end

    if data ~= nil then
        -- 屏蔽未开放的英雄头像（临时处理）
        if data['head'] then
            data['head'] = checkHeroModelId(data['head'])
        end

        if data["time"] ~= nil then
            timeCtrl.selectedIndex = 1;
            if data["Channel"] ~= Config.MsgChannel.Person then
                if G.serverData["chat"] ~= nil and G.serverData["chat"][data["Channel"]] then
                    local chatdata = G.serverData["chat"][data["Channel"]];
                    for i = 1, #chatdata do
                        if chatdata[i].time ~= nil then
                            firsttime = chatdata[1].time or chatdata[2].time
                            break;
                        end
                    end
                end
            elseif data["Channel"] == Config.MsgChannel.Person then
                if G.serverData["privateChat"] ~= nil and G.serverData["privateChat"][data["PlayerId"]] then
                    local chatdata = G.serverData["privateChat"][data["PlayerId"]];
                    for i = 1, #chatdata do
                        if chatdata[i].time ~= nil then
                            firsttime = chatdata[i].time
                            break;
                        end
                    end
                end
            end
            local _time = data["time"]/1000
            local offset = _time - firsttime

            if offset > minute  then
                _time = os.date("%H:%M:%S",_time);
                time.text = _time;
                time2.text = _time
            elseif offset == 0 then
                _time = os.date("%H:%M:%S",_time);
                time.text = _time;
                time2.text = _time
            elseif offset < minute then
                time.text = "";
                timeCtrl.selectedIndex = 0;
                time2.text = ""
            elseif offset > daytime then
                _time = os.date("%m-%d %H:%M:%S",_time);
                time.text = _time;
                time2.text = _time
            end
        end
        --print("==========>")
        --printTable(data)
        --local myselfData = logicMgr.HeroManager").getMyself();
        if this.otherLBS ~= nil then
            this.otherLBS.text = data.lbs or "";
        end
        if data.Channel == Config.MsgChannel.System then
            chatMsgCtrl.selectedIndex = 2
        elseif data["roleId"] ~=  logicMgr.HeroManager.GetRoleId() then
            chatMsgCtrl.selectedIndex= 0
        else
            chatMsgCtrl.selectedIndex = 1
        end
        if isMiniPanel then
            chatMsgCtrl.selectedIndex = 0
        end
        if data["roleId"] ~= nil and data["roleId"] ~=  logicMgr.HeroManager.GetRoleId() then
            --chatMsgCtrl.selectedPage = "notMe";
            if otherIcon then
                this.SetPlayerIcon(otherIcon:GetChild("head"):GetChild("HeadIcon"),data["head"],otherIcon:GetChild("frame"),data["headFrame"])
                SetHeadFEWithFavorLv(otherIcon,data["favorLv"] or 0)
            end
            otherName.text = "[S"..tostring(data.serverId).."]"..tostring(data["roleName"]);
            logicMgr.ChatManager.GMColor(otherName,data.roleName,default_color)

            otherDialog.text = this.ParseEmoji(data["Message"]);
            this.SetDialoglink(otherDialog,data)
            local titleId =data["titleId"];
            if otherTitle then
                if titleId~=nil and titleId~=0 then
                    otherTitle.visible = true;
                    otherTitle:GetController("show").selectedIndex = 1;
                    otherTitle:GetChild("icon").url = "ui://ICONAtlas/".. G.dataTable["t_medal"][tostring(titleId)].f_MedalPic;
                    local effect = otherTitle:GetChild("Effect_Dwsg");
                    local effect2 = otherTitle:GetChild("effect_huizsj");
                    local config = G.dataTable["t_medal"][tostring(titleId)]
                    local level = config.f_LevelId;
                    if config.f_GroupId == 6 then
                        effect2.visible = false
                        effect.visible = true
                        effect.animationName = "idle" .. level;
                        effect.skinName = level;
                        effect.loop = true;
                    else
                        effect2.visible = true
                        effect.visible = false
                    end
                else
                    otherTitle.visible = false;
                    otherTitle:GetController("show").selectedIndex = 0;
                end
            end
            --UnityEngine.UI.LayoutRebuilder.ForceRebuildLayoutImmediate(rect_normal_name);
            --UnityEngine.UI.LayoutRebuilder.ForceRebuildLayoutImmediate(rect_normal_msg);
            --rect_normal_img.anchoredPosition = Vector2(rect_normal_name.sizeDelta.x + 82,-95);
            --rect_normal_img.sizeDelta = Vector2(rect_normal_msg.sizeDelta.x + 40,80);
        elseif data["roleId"] ~= nil and data["roleId"] == logicMgr.HeroManager.GetRoleId() then
            if isMiniPanel then
                --chatMsgCtrl.selectedPage = "notMe";
                otherName.text = "[S"..data.serverId.."]"..data["roleName"];
                logicMgr.ChatManager.GMColor(otherName,data.roleName,default_color)
                otherDialog.text = this.ParseEmoji(data["Message"]);
                this.SetDialoglink(otherDialog,data)
            else
                --chatMsgCtrl.selectedPage = "isMe";
                this.SetPlayerIcon(myIcon,logicMgr.SkinManager.getHeroSkinId(data["head"]),myIconFrame,data["headFrame"])
                SetHeadFEWithModelId(obj:GetChild("myIcon"),data["head"])
                myName.text = "[S"..data.serverId.."]"..data["roleName"];
                logicMgr.ChatManager.GMColor(myName,data.roleName,default_color)
                myDialog.text = this.ParseEmoji(data["Message"]);
                this.SetDialoglink(myDialog,data)
                local titleId =data["titleId"];
                if titleId~=nil and titleId~=0 then
                    myTitle.visible = true;
                    myTitle:GetController("show").selectedIndex = 1;
                    myTitle:GetChild("icon").url = "ui://ICONAtlas/".. G.dataTable["t_medal"][tostring(titleId)].f_MedalPic;
                    local effect = myTitle:GetChild("Effect_Dwsg");
                    local effect2 = myTitle:GetChild("effect_huizsj");
                    local config = G.dataTable["t_medal"][tostring(titleId)]
                    local level = config.f_LevelId;
                    if config.f_GroupId == 6 then
                        effect2.visible = false
                        effect.visible = true
                        effect.animationName = "idle" .. level;
                        effect.skinName = level;
                        effect.loop = true;
                    else
                        effect2.visible = true
                        effect.visible = false
                    end
                else
                    myTitle.visible = false;
                    myTitle:GetController("show").selectedIndex = 0;
                end
            end
        end
    end
end
function ChatMsgItem.SetDialoglink(dialog,msgtbl)
    local isMe=msgtbl.roleId== logicMgr.HeroManager.GetRoleId()
    if isMe then
        dialog.text=string.gsub(dialog.text,"<a href='"..Config.ChatLinkType.InvasionInvite.."'>.*</a>","",1)
    else
        dialog.onClickLink:Clear()
        dialog.onClickLink:Add(function(context)
            if context.data==Config.ChatLinkType.InvasionInvite then
                if InvasionHandler.IsTeamAvaliable() then
                    if InvasionHandler.IsMyRoom() then
                        InvasionHandler.ReqJoinTeamBoss(msgtbl.roleId,1)
                        log("contextData"..context.data)
                    else
                        UISysTips.AddMsg(getLanguage("InvasionChatLeave"))
                    end
                else
                    --UISysTips.AddMsg(getLanguage("InvasionNoTeam"))
                    closeUI(PanelNames.UIChatPanel)
                    UIBottom.onClickAdventure()
                    showUI(PanelNames.UIInvasionTeam)
                end
            end
        end)
    end
end
function ChatMsgItem.ParseEmoji(str)
    --local s = str
    --for k,v in pairs(logicMgr.ChatManager.emojiTransferList) do
    --    s = string.gsub(s,v,k)
    --end
    local s = EmojiParser.inst:Parse(str);
    return s
end
function ChatMsgItem.SetPlayerIcon(iconGo,iconId,frameGo,frameId)
    if iconGo then
        local path = dataTable.getDataTableByStringId("t_skin",iconId,"f_HeroIcon");
        if not path then
            path = dataTable.getDataTableByStringId("t_hero",iconId,"f_HeroIcon")
        end
        if not path then return end
        iconGo.url = "ui://ICONAtlas/"..path;

    end
    if frameGo and frameId~=nil then
        frameGo.url = "ui://ICONAtlas/" .. frameId;
    end

    --if not iconGo then return end
    --if tonumber(iconId) ~= nil then
    --    local icon = dataTable.getDataTableByStringId("t_hero",iconId,"f_HeroIcon")
    --    if icon then
    --        iconGo.url = "ui://ICONAtlas/"..icon
    --    else
    --        logError("找不到头像 id："..iconId)
    --    end
    --else
    --    iconGo.url = iconId
    --end
end
-- --点击将音频类型的字节(字符串)转换为audioClip存入audioSource并播放
-- function ChatMsgItem.stringToAudio(audioSource,strData)
--     soundMgr:ByteToAudio(strData,audioSource);
-- end


return ChatMsgItem;